<script setup>
import { ref } from 'vue'
import websocket from "@/utils/WebSocket.js";
import {getUserService, sendMessageToService} from "@/api/WebSocket.js";
import useUserStore from "@/store/modules/user.js";
// 用户信息
const userStore = useUserStore()
const username = sessionStorage.getItem('userName')
// 收到的消息
const receivedMessage = ref('')

// 输入框中的消息
const inputMessage = ref('')
// 输入框中的用户ID
const inputUserId = ref('')

// 连接WebSocket
const connectWebSocket = async () => {
  await new Promise((resolve) => {
    websocket.Init(username)

    // 在 WebSocket 连接成功时调用 resolve
    websocket.getWebSocket().onopen = () => {
      console.log('WebSocket连接成功')
      resolve()
    }
  })

  // 使用 ref 包装 onmessage 回调
  websocket.getWebSocket().onmessage = (event) => {
    // 处理消息，这里你可以根据实际需求更新页面上的数据
    console.log('收到的消息WebSocket2:', event.data)
    // 更新收到的消息
    receivedMessage.value = event.data
  }
}

// 断开WebSocket连接
const disconnectWebSocket = () => {
  websocket.Close()
}

// 获取在线用户
const userList = ref([])
const getUserList = async () => {
  const res = await getUserService()
  userList.value = res.data
}

// 发送消息
const sendMessage = async () => {
  const userName = inputUserId.value // 使用输入框中的用户ID
  const message = inputMessage.value

  // 调用发送消息的接口
  await sendMessageToService({ message, userName })

  // 清空输入框
  // inputMessage.value = ''
}
</script>

<template>
  <div>
    <el-button type="primary" @click="connectWebSocket">连接WebSocket</el-button>
    <el-button type="danger" @click="disconnectWebSocket">断开WebSocket</el-button>
    <br />
    <!-- 输入框和按钮 -->
    <el-input v-model="inputUserId" placeholder="输入用户ID" style="width: 120px"></el-input>
    <el-input v-model="inputMessage" placeholder="输入消息"></el-input>
    <el-button type="" @click="sendMessage">发送消息</el-button>
  </div>
  <hr />
  <div>
    <span>收到的消息：{{ receivedMessage }}</span>
  </div>
  <hr />
  <div>
    <el-button type="primary" @click="getUserList">获取在线用户列表</el-button>
    <div class="userList">
      <ul>
        <li v-for="item in userList" :key="item.index">
          {{ item }}
        </li>
      </ul>
    </div>
    <div>
<!--      <span>有缺点无法获取实时数据，必须断开在连接，应该是由于不是和登录一个作用域导致的</span>-->
    </div>
  </div>
</template>

<style scoped>
.userList {
  background-color: pink;
}
</style>

